/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * PreferencesJFrame.java
 *
 * Created on 04-Jul-2011, 13:38:05
 */
package picasaphotomanager.JFrames;

import configuration.ConfigurationManager;
import configuration.Defaults;
import configuration.Preferences;
import configuration.PicasaAccount;
import java.io.File;
import java.io.IOException;
import java.lang.Math;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.DefaultListModel;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.border.TitledBorder;
import javax.swing.filechooser.FileSystemView;
import utilities.DataFormater;

/**
 *
 * @author zalem1
 */
public class PreferencesJFrame extends javax.swing.JFrame {
    private String _titlePrefix;
    private PicasaAccount _selectedAccount;
    private static PreferencesJFrame _classInstance = null;
    private JFrame _parent;
    
    public static PreferencesJFrame getInstance(JFrame parent) {
        if (_classInstance == null)
            _classInstance = new PreferencesJFrame();
        
        _classInstance._parent = parent;
        
        return _classInstance;
    }
    
    /** Creates new form PreferencesJFrame */
    private PreferencesJFrame() {       
        initComponents();

        AccountsList.setModel(new DefaultListModel());
        _titlePrefix = getTitle();

        try {
            setIconImage(ImageIO.read(getClass().getResource("/resources/images/Settings-16.png")));
        } catch (IOException ex) {
            Logger.getLogger(PreferencesJFrame.class.getName()).log(Level.SEVERE, "Error while loading icon for the preferences frame.", ex);
        }   
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        jTabbedPane1 = new javax.swing.JTabbedPane();
        UserAccountsPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        AccountsList = new javax.swing.JList();
        AddAccountButton = new javax.swing.JButton();
        RemoveAccountButton = new javax.swing.JButton();
        AccountDetailsPanel = new javax.swing.JPanel();
        AccountNameLabel = new javax.swing.JLabel();
        AccountNameTextField = new javax.swing.JTextField();
        UsernameLabel = new javax.swing.JLabel();
        UsernameTextField = new javax.swing.JTextField();
        PasswordLabel = new javax.swing.JLabel();
        ConnectManuallyCheckBox = new javax.swing.JCheckBox();
        PasswordTextField = new javax.swing.JPasswordField();
        SaveAccountButton = new javax.swing.JButton();
        SynchronisationOptionsPanel = new javax.swing.JPanel();
        poolingIntervalPanel = new javax.swing.JPanel();
        poolingIntervalSlider = new javax.swing.JSlider();
        autoSyncNewAlbumsCheckBox = new javax.swing.JCheckBox();
        jLabel1 = new javax.swing.JLabel();
        defaultSyncFolderTextField = new javax.swing.JTextField();
        jButton2 = new javax.swing.JButton();
        SaveSyncButton = new javax.swing.JButton();
        downloadPhotosAlbumsCheckBox = new javax.swing.JCheckBox();
        downloadVideosAlbumsCheckBox = new javax.swing.JCheckBox();
        DefaultResolutionLabel = new javax.swing.JLabel();
        DefaultResolutionComboBox = new javax.swing.JComboBox();
        ProxyPanel = new javax.swing.JPanel();
        HttpProxyHostLabel = new javax.swing.JLabel();
        HttpProxyPortLabel = new javax.swing.JLabel();
        HttpProxyHostTextField = new javax.swing.JTextField();
        HttpProxyPortTextField = new javax.swing.JTextField();
        HttpsProxyHostLabel = new javax.swing.JLabel();
        HttpsProxyHostTextField = new javax.swing.JTextField();
        HttpsProxyPortLabel = new javax.swing.JLabel();
        HttpsProxyPortTextField = new javax.swing.JTextField();
        ProxyUsernameTextField = new javax.swing.JTextField();
        ProxyUsernameLabel = new javax.swing.JLabel();
        ProxyPasswordLabel = new javax.swing.JLabel();
        ProxyPasswordField = new javax.swing.JPasswordField();
        SaveProxyButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Preferences");
        setLocationByPlatform(true);
        setName("PreferencesFrame"); // NOI18N
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowOpened(java.awt.event.WindowEvent evt) {
                formWindowOpened(evt);
            }
        });

        AccountsList.addListSelectionListener(new javax.swing.event.ListSelectionListener() {
            public void valueChanged(javax.swing.event.ListSelectionEvent evt) {
                AccountsListValueChanged(evt);
            }
        });
        jScrollPane1.setViewportView(AccountsList);

        AddAccountButton.setText("+");
        AddAccountButton.setMargin(new java.awt.Insets(2, 5, 2, 5));
        AddAccountButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AddAccountButtonActionPerformed(evt);
            }
        });

        RemoveAccountButton.setText("-");
        RemoveAccountButton.setMargin(new java.awt.Insets(2, 7, 2, 7));
        RemoveAccountButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                RemoveAccountButtonActionPerformed(evt);
            }
        });

        AccountDetailsPanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        AccountDetailsPanel.setEnabled(false);

        AccountNameLabel.setText("Account name:");

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, AccountDetailsPanel, org.jdesktop.beansbinding.ELProperty.create("${enabled}"), AccountNameLabel, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, AccountDetailsPanel, org.jdesktop.beansbinding.ELProperty.create("${enabled}"), AccountNameTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        AccountNameTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AccountNameTextFieldActionPerformed(evt);
            }
        });

        UsernameLabel.setText("Username:");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, AccountDetailsPanel, org.jdesktop.beansbinding.ELProperty.create("${enabled}"), UsernameLabel, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, AccountDetailsPanel, org.jdesktop.beansbinding.ELProperty.create("${enabled}"), UsernameTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        PasswordLabel.setText("Password:");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, AccountDetailsPanel, org.jdesktop.beansbinding.ELProperty.create("${enabled}"), PasswordLabel, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        ConnectManuallyCheckBox.setText("Connect Manually");
        ConnectManuallyCheckBox.setAutoscrolls(true);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, AccountDetailsPanel, org.jdesktop.beansbinding.ELProperty.create("${enabled}"), ConnectManuallyCheckBox, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, AccountDetailsPanel, org.jdesktop.beansbinding.ELProperty.create("${enabled}"), PasswordTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        SaveAccountButton.setText("Save");

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, AccountDetailsPanel, org.jdesktop.beansbinding.ELProperty.create("${enabled}"), SaveAccountButton, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        SaveAccountButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveAccountButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout AccountDetailsPanelLayout = new javax.swing.GroupLayout(AccountDetailsPanel);
        AccountDetailsPanel.setLayout(AccountDetailsPanelLayout);
        AccountDetailsPanelLayout.setHorizontalGroup(
            AccountDetailsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(AccountDetailsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(AccountDetailsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(AccountDetailsPanelLayout.createSequentialGroup()
                        .addComponent(AccountNameLabel)
                        .addGap(2, 2, 2)
                        .addComponent(AccountNameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 249, Short.MAX_VALUE))
                    .addGroup(AccountDetailsPanelLayout.createSequentialGroup()
                        .addGroup(AccountDetailsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(UsernameLabel)
                            .addComponent(PasswordLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(AccountDetailsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(UsernameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE)
                            .addComponent(PasswordTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 267, Short.MAX_VALUE)))
                    .addComponent(ConnectManuallyCheckBox)
                    .addComponent(SaveAccountButton, javax.swing.GroupLayout.Alignment.TRAILING))
                .addContainerGap())
        );
        AccountDetailsPanelLayout.setVerticalGroup(
            AccountDetailsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(AccountDetailsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(AccountDetailsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(AccountNameLabel)
                    .addComponent(AccountNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(AccountDetailsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(UsernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(UsernameLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(AccountDetailsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(PasswordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(PasswordLabel))
                .addGap(18, 18, 18)
                .addComponent(ConnectManuallyCheckBox)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 137, Short.MAX_VALUE)
                .addComponent(SaveAccountButton)
                .addContainerGap())
        );

        javax.swing.GroupLayout UserAccountsPanelLayout = new javax.swing.GroupLayout(UserAccountsPanel);
        UserAccountsPanel.setLayout(UserAccountsPanelLayout);
        UserAccountsPanelLayout.setHorizontalGroup(
            UserAccountsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(UserAccountsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(UserAccountsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(UserAccountsPanelLayout.createSequentialGroup()
                        .addComponent(AddAccountButton, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(RemoveAccountButton, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(UserAccountsPanelLayout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(AccountDetailsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );
        UserAccountsPanelLayout.setVerticalGroup(
            UserAccountsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(UserAccountsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(UserAccountsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 299, Short.MAX_VALUE)
                    .addComponent(AccountDetailsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addGroup(UserAccountsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(AddAccountButton)
                    .addComponent(RemoveAccountButton))
                .addContainerGap())
        );

        jTabbedPane1.addTab("User Accounts", UserAccountsPanel);

        poolingIntervalPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Sync every "));

        poolingIntervalSlider.addChangeListener(new javax.swing.event.ChangeListener() {
            public void stateChanged(javax.swing.event.ChangeEvent evt) {
                poolingIntervalSliderStateChanged(evt);
            }
        });

        javax.swing.GroupLayout poolingIntervalPanelLayout = new javax.swing.GroupLayout(poolingIntervalPanel);
        poolingIntervalPanel.setLayout(poolingIntervalPanelLayout);
        poolingIntervalPanelLayout.setHorizontalGroup(
            poolingIntervalPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(poolingIntervalPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(poolingIntervalSlider, javax.swing.GroupLayout.DEFAULT_SIZE, 435, Short.MAX_VALUE)
                .addContainerGap())
        );
        poolingIntervalPanelLayout.setVerticalGroup(
            poolingIntervalPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, poolingIntervalPanelLayout.createSequentialGroup()
                .addComponent(poolingIntervalSlider, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        autoSyncNewAlbumsCheckBox.setText("Automaticaly sync new albums");

        jLabel1.setText("Default sync folder:");

        jButton2.setText("...");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        SaveSyncButton.setText("Save");
        SaveSyncButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveSyncButtonActionPerformed(evt);
            }
        });

        downloadPhotosAlbumsCheckBox.setText("Download photos");
        downloadPhotosAlbumsCheckBox.setEnabled(false);

        downloadVideosAlbumsCheckBox.setText("Download videos");
        downloadVideosAlbumsCheckBox.setEnabled(false);

        DefaultResolutionLabel.setText("Default photo resolution:");

        DefaultResolutionComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Original resolution", "Large", "Medium", "Small" }));

        javax.swing.GroupLayout SynchronisationOptionsPanelLayout = new javax.swing.GroupLayout(SynchronisationOptionsPanel);
        SynchronisationOptionsPanel.setLayout(SynchronisationOptionsPanelLayout);
        SynchronisationOptionsPanelLayout.setHorizontalGroup(
            SynchronisationOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(SynchronisationOptionsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(SynchronisationOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, SynchronisationOptionsPanelLayout.createSequentialGroup()
                        .addComponent(poolingIntervalPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(SaveSyncButton)
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, SynchronisationOptionsPanelLayout.createSequentialGroup()
                        .addGroup(SynchronisationOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, SynchronisationOptionsPanelLayout.createSequentialGroup()
                                .addComponent(DefaultResolutionLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(DefaultResolutionComboBox, 0, 377, Short.MAX_VALUE))
                            .addGroup(SynchronisationOptionsPanelLayout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(defaultSyncFolderTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 402, Short.MAX_VALUE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(20, 20, 20))
                    .addGroup(SynchronisationOptionsPanelLayout.createSequentialGroup()
                        .addGroup(SynchronisationOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(downloadVideosAlbumsCheckBox, javax.swing.GroupLayout.PREFERRED_SIZE, 278, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(downloadPhotosAlbumsCheckBox, javax.swing.GroupLayout.PREFERRED_SIZE, 278, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(autoSyncNewAlbumsCheckBox, javax.swing.GroupLayout.PREFERRED_SIZE, 278, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap(274, Short.MAX_VALUE))))
        );
        SynchronisationOptionsPanelLayout.setVerticalGroup(
            SynchronisationOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(SynchronisationOptionsPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(SynchronisationOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(defaultSyncFolderTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(SynchronisationOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(SynchronisationOptionsPanelLayout.createSequentialGroup()
                        .addGap(11, 11, 11)
                        .addGroup(SynchronisationOptionsPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(DefaultResolutionLabel)
                            .addComponent(DefaultResolutionComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addComponent(autoSyncNewAlbumsCheckBox)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(downloadPhotosAlbumsCheckBox)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(downloadVideosAlbumsCheckBox)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 138, Short.MAX_VALUE)
                        .addComponent(poolingIntervalPanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(SaveSyncButton))
                .addContainerGap())
        );

        jTabbedPane1.addTab("Synchronisation Options", SynchronisationOptionsPanel);

        HttpProxyHostLabel.setText("HTTP proxy host:");

        HttpProxyPortLabel.setText("Port:");

        HttpProxyPortTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                HttpProxyPortTextFieldActionPerformed(evt);
            }
        });

        HttpsProxyHostLabel.setText("HTTPS proxy host:");

        HttpsProxyPortLabel.setText("Port:");

        HttpsProxyPortTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                HttpsProxyPortTextFieldActionPerformed(evt);
            }
        });

        ProxyUsernameLabel.setText("Proxy username:");

        ProxyPasswordLabel.setText("Proxy password:");

        SaveProxyButton.setText("Save");
        SaveProxyButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                SaveProxyButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout ProxyPanelLayout = new javax.swing.GroupLayout(ProxyPanel);
        ProxyPanel.setLayout(ProxyPanelLayout);
        ProxyPanelLayout.setHorizontalGroup(
            ProxyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, ProxyPanelLayout.createSequentialGroup()
                .addContainerGap(495, Short.MAX_VALUE)
                .addComponent(SaveProxyButton)
                .addContainerGap())
            .addGroup(ProxyPanelLayout.createSequentialGroup()
                .addGap(71, 71, 71)
                .addGroup(ProxyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(ProxyPanelLayout.createSequentialGroup()
                        .addGap(7, 7, 7)
                        .addComponent(HttpProxyHostLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(HttpProxyHostTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 234, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(HttpProxyPortLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(HttpProxyPortTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(ProxyPanelLayout.createSequentialGroup()
                        .addGroup(ProxyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(ProxyPanelLayout.createSequentialGroup()
                                .addGap(12, 12, 12)
                                .addComponent(ProxyUsernameLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(ProxyUsernameTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE))
                            .addGroup(ProxyPanelLayout.createSequentialGroup()
                                .addComponent(HttpsProxyHostLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(HttpsProxyHostTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 235, Short.MAX_VALUE))
                            .addGroup(ProxyPanelLayout.createSequentialGroup()
                                .addGap(13, 13, 13)
                                .addComponent(ProxyPasswordLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(ProxyPasswordField, javax.swing.GroupLayout.DEFAULT_SIZE, 231, Short.MAX_VALUE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(HttpsProxyPortLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(HttpsProxyPortTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(86, 86, 86))
        );
        ProxyPanelLayout.setVerticalGroup(
            ProxyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, ProxyPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(ProxyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(HttpProxyHostLabel)
                    .addComponent(HttpProxyHostTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(HttpProxyPortLabel)
                    .addComponent(HttpProxyPortTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(ProxyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(HttpsProxyHostLabel)
                    .addComponent(HttpsProxyHostTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(HttpsProxyPortLabel)
                    .addComponent(HttpsProxyPortTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(ProxyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ProxyUsernameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(ProxyUsernameLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(ProxyPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(ProxyPasswordLabel)
                    .addComponent(ProxyPasswordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 207, Short.MAX_VALUE)
                .addComponent(SaveProxyButton)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Proxy", ProxyPanel);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 567, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 390, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane1.getAccessibleContext().setAccessibleName("Preferences");

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void AccountNameTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AccountNameTextFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_AccountNameTextFieldActionPerformed

    private void formWindowOpened(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowOpened
        RefreshAccountList();
    }//GEN-LAST:event_formWindowOpened

    private void AddAccountButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AddAccountButtonActionPerformed
        ClearAccountDetailsPane();
        AccountDetailsPanel.setEnabled(true);
        AccountsList.clearSelection();
        _selectedAccount = null;
    }//GEN-LAST:event_AddAccountButtonActionPerformed

    private void RemoveAccountButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_RemoveAccountButtonActionPerformed
        PicasaAccount accountToRemove = (PicasaAccount)AccountsList.getSelectedValue();
        
        ConfigurationManager.GetPreferences().getUserAccounts().remove(accountToRemove);
        
        RefreshAccountList();
        ClearAccountDetailsPane();
        AccountDetailsPanel.setEnabled(false);
    }//GEN-LAST:event_RemoveAccountButtonActionPerformed

    private void AccountsListValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_AccountsListValueChanged
         if (!evt.getValueIsAdjusting()) {
            // Get all selected items
            Object selected = AccountsList.getSelectedValue();
            RemoveAccountButton.setEnabled(selected != null);
            
            if (selected == null || !(selected instanceof PicasaAccount)) {
                setTitle(_titlePrefix);
                return;
            }

            PicasaAccount account = (PicasaAccount)selected;
            _selectedAccount = account;
            
            //Set window title
            setTitle(_titlePrefix + " - " + account.getPicasaName());
            
            AccountScreen_Read(account);
            
            AccountDetailsPanel.setEnabled(true);
        }
    }//GEN-LAST:event_AccountsListValueChanged

    private void SaveAccountButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveAccountButtonActionPerformed
        for (int accountIndex = 0; accountIndex < AccountsList.getModel().getSize(); accountIndex++) {
            PicasaAccount account = (PicasaAccount)AccountsList.getModel().getElementAt(accountIndex);
            
            if (account == _selectedAccount) {
                //Update account
                AccountScreen_Write(account);
                RefreshAccountList();
                return;
            }            
        }
        
        //Add new account
        PicasaAccount newAccount = new PicasaAccount();
        AccountScreen_Write(newAccount);
        
        ConfigurationManager.GetPreferences().getUserAccounts().add(newAccount);
        _selectedAccount = newAccount;
        RefreshAccountList();        
    }//GEN-LAST:event_SaveAccountButtonActionPerformed

    private void HttpProxyPortTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HttpProxyPortTextFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_HttpProxyPortTextFieldActionPerformed

    private void HttpsProxyPortTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_HttpsProxyPortTextFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_HttpsProxyPortTextFieldActionPerformed

    private void SaveProxyButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveProxyButtonActionPerformed
        ProxyScreen_Write();
    }//GEN-LAST:event_SaveProxyButtonActionPerformed

    private void poolingIntervalSliderStateChanged(javax.swing.event.ChangeEvent evt) {//GEN-FIRST:event_poolingIntervalSliderStateChanged
        updatePoolingIntervalString();
    }//GEN-LAST:event_poolingIntervalSliderStateChanged

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        if (_parent != null) { 
            _parent.setEnabled(true);
            _parent.toFront();
        }
    }//GEN-LAST:event_formWindowClosed

    private void SaveSyncButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SaveSyncButtonActionPerformed
        SyncScreen_Write();
    }//GEN-LAST:event_SaveSyncButtonActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        JFileChooser fileChooser = new JFileChooser(FileSystemView.getFileSystemView());
        fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        fileChooser.setSelectedFile(new File(defaultSyncFolderTextField.getText()));
        
        if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            defaultSyncFolderTextField.setText(fileChooser.getSelectedFile().getPath());
        }
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new PreferencesJFrame().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel AccountDetailsPanel;
    private javax.swing.JLabel AccountNameLabel;
    private javax.swing.JTextField AccountNameTextField;
    private javax.swing.JList AccountsList;
    private javax.swing.JButton AddAccountButton;
    private javax.swing.JCheckBox ConnectManuallyCheckBox;
    private javax.swing.JComboBox DefaultResolutionComboBox;
    private javax.swing.JLabel DefaultResolutionLabel;
    private javax.swing.JLabel HttpProxyHostLabel;
    private javax.swing.JTextField HttpProxyHostTextField;
    private javax.swing.JLabel HttpProxyPortLabel;
    private javax.swing.JTextField HttpProxyPortTextField;
    private javax.swing.JLabel HttpsProxyHostLabel;
    private javax.swing.JTextField HttpsProxyHostTextField;
    private javax.swing.JLabel HttpsProxyPortLabel;
    private javax.swing.JTextField HttpsProxyPortTextField;
    private javax.swing.JLabel PasswordLabel;
    private javax.swing.JPasswordField PasswordTextField;
    private javax.swing.JPanel ProxyPanel;
    private javax.swing.JPasswordField ProxyPasswordField;
    private javax.swing.JLabel ProxyPasswordLabel;
    private javax.swing.JLabel ProxyUsernameLabel;
    private javax.swing.JTextField ProxyUsernameTextField;
    private javax.swing.JButton RemoveAccountButton;
    private javax.swing.JButton SaveAccountButton;
    private javax.swing.JButton SaveProxyButton;
    private javax.swing.JButton SaveSyncButton;
    private javax.swing.JPanel SynchronisationOptionsPanel;
    private javax.swing.JPanel UserAccountsPanel;
    private javax.swing.JLabel UsernameLabel;
    private javax.swing.JTextField UsernameTextField;
    private javax.swing.JCheckBox autoSyncNewAlbumsCheckBox;
    private javax.swing.JTextField defaultSyncFolderTextField;
    private javax.swing.JCheckBox downloadPhotosAlbumsCheckBox;
    private javax.swing.JCheckBox downloadVideosAlbumsCheckBox;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JPanel poolingIntervalPanel;
    private javax.swing.JSlider poolingIntervalSlider;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    private void RefreshAccountList() {
        //Clear the model
        DefaultListModel model = (DefaultListModel) AccountsList.getModel();
        model.clear();

        //Add user accounts to the model
        for (PicasaAccount account : ConfigurationManager.GetPreferences().getUserAccounts())
        {
            model.addElement(account);
        }
        
        AccountsList.setSelectedValue(_selectedAccount, true);
    }
    
    private void ClearAccountDetailsPane()
    {
        AccountNameTextField.setText("");
        UsernameTextField.setText("");
        PasswordTextField.setText("");
        ConnectManuallyCheckBox.setSelected(false);
    }
    
    private void AccountScreen_Write(PicasaAccount account)
    {
        account.setPicasaName(AccountNameTextField.getText());
        account.setLoginUsername(UsernameTextField.getText());
        account.setLoginPassword(PasswordTextField.getText());
        account.setConnectManually(ConnectManuallyCheckBox.isSelected());
    } 
    
    private void AccountScreen_Read(PicasaAccount account) {
            AccountNameTextField.setText(account.getPicasaName());
            UsernameTextField.setText(account.getLoginUsername());
            PasswordTextField.setText(account.getLoginPassword());
            ConnectManuallyCheckBox.setSelected(account.getConnectManually());
    }
    
    private void SyncScreen_Write()
    {
        Preferences configuration = ConfigurationManager.GetPreferences();
        
        configuration.setDefaultPhotoFolder(defaultSyncFolderTextField.getText());
        configuration.setDefaultResolution(getResolutionFromDropdown(DefaultResolutionComboBox.getSelectedIndex())); 
        configuration.setAutoSyncNewAlbums(autoSyncNewAlbumsCheckBox.isSelected());
        configuration.setDownloadPhotos(downloadPhotosAlbumsCheckBox.isSelected());
        configuration.setDownloadVideos(downloadVideosAlbumsCheckBox.isSelected());
        
        configuration.setPoolingInterval(getPoolingFromSlider(poolingIntervalSlider.getValue()));
    }
    
    private void SyncScreen_Read()
    {
        Preferences configuration = ConfigurationManager.GetPreferences();
        
        defaultSyncFolderTextField.setText(configuration.getDefaultPhotoFolder());
        DefaultResolutionComboBox.setSelectedIndex(getResolutionFromConfig(configuration.getDefaultResolution()));
        autoSyncNewAlbumsCheckBox.setSelected(configuration.getAutoSyncNewAlbums());
        downloadPhotosAlbumsCheckBox.setSelected(configuration.getDownloadPhotos());
        downloadVideosAlbumsCheckBox.setSelected(configuration.getDownloadVideos());
        
        poolingIntervalSlider.setValue(getPoolingFromConfig(configuration.getPoolingInterval()));
    }    
    
    private void ProxyScreen_Read() {
        Preferences configuration = ConfigurationManager.GetPreferences();
        HttpProxyHostTextField.setText(configuration.getHttpProxyHost());
        HttpProxyPortTextField.setText(configuration.getHttpProxyPort());
        HttpsProxyHostTextField.setText(configuration.getHttpsProxyHost());
        HttpsProxyPortTextField.setText(configuration.getHttpsProxyPort());

        ProxyUsernameTextField.setText(configuration.getProxyUsername());
        ProxyPasswordField.setText(configuration.getProxyPassword());        
    }

    private void ProxyScreen_Write() {
        Preferences configuration = ConfigurationManager.GetPreferences();
        configuration.setHttpProxyHost(HttpProxyHostTextField.getText());
        configuration.setHttpProxyPort(HttpProxyPortTextField.getText());
        configuration.setHttpsProxyHost(HttpsProxyHostTextField.getText());
        configuration.setHttpsProxyPort(HttpsProxyPortTextField.getText());
        
        configuration.setProxyUsername(ProxyUsernameTextField.getText());
        configuration.setProxyPassword(ProxyPasswordField.getText());    
    }    
    
    
    private long getPoolingFromSlider(int value)
    {
        long poolingInterval = (value * value) + 30;
        return poolingInterval * 1000;
    }

    private int getPoolingFromConfig(long value)
    {
        double sliderValue = value / 1000;
        sliderValue -= 30;
        sliderValue = Math.sqrt(sliderValue);
        
        return (int)sliderValue;
    }

    private void updatePoolingIntervalString() {
        Long poolingInterval = getPoolingFromSlider(poolingIntervalSlider.getValue());

        ((TitledBorder)poolingIntervalPanel.getBorder()).setTitle("Pooling interval:" + DataFormater.GetHumanReadableTime(poolingInterval));
        poolingIntervalPanel.repaint();
    }

    @Override
    public void setVisible(boolean b) {
        super.setVisible(b);
        if (_parent != null) _parent.setEnabled(false);
        
        SyncScreen_Read();
        ProxyScreen_Read();
    }

    public static int getResolutionFromConfig(String defaultResolution) {
        for (Integer res : Defaults.SupportedResolutions)
            if (res.toString().equalsIgnoreCase(defaultResolution)) {
                if (res.equals(Defaults.SmallResolution)) return 3;
                else if (res.equals(Defaults.MediumResolution)) return 2;
                else if (res.equals(Defaults.LargeResolution)) return 1;
                else if (res.equals(-1)) return 0;
            }
        
        Logger.getLogger(PreferencesJFrame.class.getName()).log(Level.SEVERE, "Default image resolution read from the configuration {0} doesn''t match any of the pre-set categories (i.e. Large, Small or Medium). Reseting to the default value.", defaultResolution);
        return getResolutionFromConfig(Defaults.DefaultResolution.toString());
    }

    public static String getResolutionFromDropdown(int selectedIndex) {
        if (selectedIndex == 0) return "-1";
        else if (selectedIndex == 1) return Defaults.LargeResolution.toString();
        else if (selectedIndex == 2) return Defaults.MediumResolution.toString();
        else if (selectedIndex == 3) return Defaults.SmallResolution.toString();
        else return Defaults.DefaultResolution.toString();
    }


}
